import React, { useState } from 'react'
import { 
  Drawer, 
  List, 
  Input, 
  Button, 
  Space, 
  Typography, 
  Tag, 
  Tooltip,
  Modal,
  Form,
  message,
  Popconfirm,
  Divider,
} from 'antd'
import {
  CodeOutlined,
  SearchOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  CopyOutlined,
  StarOutlined,
  StarFilled,
} from '@ant-design/icons'
import { useLocalStorage } from '@/hooks/useLocalStorage'

const { Search } = Input
const { Text, Paragraph } = Typography
const { TextArea } = Input

interface SQLSnippet {
  id: string
  name: string
  description: string
  sql: string
  tags: string[]
  category: string
  isFavorite: boolean
  createdAt: string
  usageCount: number
}

interface SQLSnippetsProps {
  visible: boolean
  onClose: () => void
  onInsertSnippet?: (sql: string) => void
}

// 预定义的代码片段
const DEFAULT_SNIPPETS: SQLSnippet[] = [
  {
    id: '1',
    name: '基础查询',
    description: '基本的SELECT查询模板',
    sql: 'SELECT ${1:columns}\nFROM ${2:table_name}\nWHERE ${3:condition}\nORDER BY ${4:column}\nLIMIT ${5:10};',
    tags: ['select', 'basic'],
    category: '查询',
    isFavorite: false,
    createdAt: new Date().toISOString(),
    usageCount: 0,
  },
  {
    id: '2',
    name: '连接查询',
    description: '多表连接查询模板',
    sql: 'SELECT ${1:a.column1, b.column2}\nFROM ${2:table1} a\nINNER JOIN ${3:table2} b ON a.${4:id} = b.${5:foreign_id}\nWHERE ${6:condition};',
    tags: ['join', 'select'],
    category: '查询',
    isFavorite: false,
    createdAt: new Date().toISOString(),
    usageCount: 0,
  },
  {
    id: '3',
    name: '插入数据',
    description: '插入数据模板',
    sql: 'INSERT INTO ${1:table_name} (${2:column1, column2, column3})\nVALUES (${3:value1, value2, value3});',
    tags: ['insert', 'dml'],
    category: '数据操作',
    isFavorite: false,
    createdAt: new Date().toISOString(),
    usageCount: 0,
  },
  {
    id: '4',
    name: '更新数据',
    description: '更新数据模板',
    sql: 'UPDATE ${1:table_name}\nSET ${2:column1} = ${3:value1},\n    ${4:column2} = ${5:value2}\nWHERE ${6:condition};',
    tags: ['update', 'dml'],
    category: '数据操作',
    isFavorite: false,
    createdAt: new Date().toISOString(),
    usageCount: 0,
  },
  {
    id: '5',
    name: '删除数据',
    description: '删除数据模板',
    sql: 'DELETE FROM ${1:table_name}\nWHERE ${2:condition};',
    tags: ['delete', 'dml'],
    category: '数据操作',
    isFavorite: false,
    createdAt: new Date().toISOString(),
    usageCount: 0,
  },
  {
    id: '6',
    name: '创建表',
    description: '创建表模板',
    sql: 'CREATE TABLE ${1:table_name} (\n    ${2:id} INT AUTO_INCREMENT PRIMARY KEY,\n    ${3:column1} VARCHAR(255) NOT NULL,\n    ${4:column2} TEXT,\n    ${5:created_at} TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n);',
    tags: ['create', 'ddl', 'table'],
    category: '表结构',
    isFavorite: false,
    createdAt: new Date().toISOString(),
    usageCount: 0,
  },
  {
    id: '7',
    name: '窗口函数',
    description: '窗口函数查询模板',
    sql: 'SELECT ${1:column1},\n       ${2:column2},\n       ROW_NUMBER() OVER (PARTITION BY ${3:partition_column} ORDER BY ${4:order_column}) as rn\nFROM ${5:table_name}\nWHERE ${6:condition};',
    tags: ['window', 'advanced'],
    category: '高级查询',
    isFavorite: false,
    createdAt: new Date().toISOString(),
    usageCount: 0,
  },
  {
    id: '8',
    name: 'CTE查询',
    description: '公共表表达式查询模板',
    sql: 'WITH ${1:cte_name} AS (\n    SELECT ${2:columns}\n    FROM ${3:table_name}\n    WHERE ${4:condition}\n)\nSELECT ${5:columns}\nFROM ${1:cte_name}\nWHERE ${6:condition};',
    tags: ['cte', 'with', 'advanced'],
    category: '高级查询',
    isFavorite: false,
    createdAt: new Date().toISOString(),
    usageCount: 0,
  },
]

const SQLSnippets: React.FC<SQLSnippetsProps> = ({
  visible,
  onClose,
  onInsertSnippet,
}) => {
  const [snippets, setSnippets] = useLocalStorage<SQLSnippet[]>('sql-snippets', DEFAULT_SNIPPETS)
  const [searchKeyword, setSearchKeyword] = useState('')
  const [selectedCategory, setSelectedCategory] = useState<string>('all')
  const [editModalVisible, setEditModalVisible] = useState(false)
  const [editingSnippet, setEditingSnippet] = useState<SQLSnippet | null>(null)
  const [form] = Form.useForm()

  // 过滤代码片段
  const filteredSnippets = snippets.filter(snippet => {
    const matchesSearch = !searchKeyword || 
      snippet.name.toLowerCase().includes(searchKeyword.toLowerCase()) ||
      snippet.description.toLowerCase().includes(searchKeyword.toLowerCase()) ||
      snippet.tags.some(tag => tag.toLowerCase().includes(searchKeyword.toLowerCase()))
    
    const matchesCategory = selectedCategory === 'all' || 
      selectedCategory === 'favorites' ? snippet.isFavorite : snippet.category === selectedCategory

    return matchesSearch && matchesCategory
  })

  // 获取所有分类
  const categories = ['all', 'favorites', ...Array.from(new Set(snippets.map(s => s.category)))]

  // 处理插入代码片段
  const handleInsertSnippet = (snippet: SQLSnippet) => {
    if (onInsertSnippet) {
      // 更新使用次数
      const updatedSnippets = snippets.map(s => 
        s.id === snippet.id ? { ...s, usageCount: s.usageCount + 1 } : s
      )
      setSnippets(updatedSnippets)
      
      // 处理模板变量
      let processedSQL = snippet.sql
      // 简单的模板变量处理，将 ${n:text} 替换为 text
      processedSQL = processedSQL.replace(/\$\{\d+:([^}]+)\}/g, '$1')
      
      onInsertSnippet(processedSQL)
      message.success(`已插入代码片段: ${snippet.name}`)
    }
  }

  // 切换收藏状态
  const toggleFavorite = (snippetId: string) => {
    const updatedSnippets = snippets.map(snippet =>
      snippet.id === snippetId 
        ? { ...snippet, isFavorite: !snippet.isFavorite }
        : snippet
    )
    setSnippets(updatedSnippets)
  }

  // 编辑代码片段
  const handleEditSnippet = (snippet: SQLSnippet) => {
    setEditingSnippet(snippet)
    form.setFieldsValue({
      name: snippet.name,
      description: snippet.description,
      sql: snippet.sql,
      tags: snippet.tags.join(', '),
      category: snippet.category,
    })
    setEditModalVisible(true)
  }

  // 新建代码片段
  const handleNewSnippet = () => {
    setEditingSnippet(null)
    form.resetFields()
    setEditModalVisible(true)
  }

  // 保存代码片段
  const handleSaveSnippet = async () => {
    try {
      const values = await form.validateFields()
      const tags = values.tags ? values.tags.split(',').map((tag: string) => tag.trim()).filter(Boolean) : []
      
      const snippetData = {
        name: values.name,
        description: values.description,
        sql: values.sql,
        tags,
        category: values.category,
      }

      if (editingSnippet) {
        // 更新现有片段
        const updatedSnippets = snippets.map(snippet =>
          snippet.id === editingSnippet.id
            ? { ...snippet, ...snippetData }
            : snippet
        )
        setSnippets(updatedSnippets)
        message.success('代码片段已更新')
      } else {
        // 创建新片段
        const newSnippet: SQLSnippet = {
          id: Date.now().toString(),
          ...snippetData,
          isFavorite: false,
          createdAt: new Date().toISOString(),
          usageCount: 0,
        }
        setSnippets([...snippets, newSnippet])
        message.success('代码片段已创建')
      }

      setEditModalVisible(false)
      setEditingSnippet(null)
      form.resetFields()
    } catch (error) {
      console.error('保存代码片段失败:', error)
    }
  }

  // 删除代码片段
  const handleDeleteSnippet = (snippetId: string) => {
    const updatedSnippets = snippets.filter(snippet => snippet.id !== snippetId)
    setSnippets(updatedSnippets)
    message.success('代码片段已删除')
  }

  // 复制代码片段
  const handleCopySnippet = (snippet: SQLSnippet) => {
    navigator.clipboard.writeText(snippet.sql).then(() => {
      message.success('代码已复制到剪贴板')
    }).catch(() => {
      message.error('复制失败')
    })
  }

  return (
    <>
      <Drawer
        title="SQL代码片段"
        width={600}
        open={visible}
        onClose={onClose}
        extra={
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={handleNewSnippet}
          >
            新建片段
          </Button>
        }
      >
        {/* 搜索和过滤 */}
        <Space direction="vertical" style={{ width: '100%', marginBottom: 16 }}>
          <Search
            placeholder="搜索代码片段..."
            value={searchKeyword}
            onChange={(e) => setSearchKeyword(e.target.value)}
            allowClear
          />
          
          <Space wrap>
            {categories.map(category => (
              <Button
                key={category}
                size="small"
                type={selectedCategory === category ? 'primary' : 'default'}
                onClick={() => setSelectedCategory(category)}
              >
                {category === 'all' ? '全部' : 
                 category === 'favorites' ? '收藏' : category}
                {category !== 'all' && category !== 'favorites' && (
                  <span style={{ marginLeft: 4, opacity: 0.7 }}>
                    ({snippets.filter(s => s.category === category).length})
                  </span>
                )}
              </Button>
            ))}
          </Space>
        </Space>

        {/* 代码片段列表 */}
        <List
          dataSource={filteredSnippets}
          renderItem={(snippet) => (
            <List.Item
              actions={[
                <Tooltip title="收藏">
                  <Button
                    type="text"
                    size="small"
                    icon={snippet.isFavorite ? <StarFilled style={{ color: '#faad14' }} /> : <StarOutlined />}
                    onClick={() => toggleFavorite(snippet.id)}
                  />
                </Tooltip>,
                <Tooltip title="复制">
                  <Button
                    type="text"
                    size="small"
                    icon={<CopyOutlined />}
                    onClick={() => handleCopySnippet(snippet)}
                  />
                </Tooltip>,
                <Tooltip title="编辑">
                  <Button
                    type="text"
                    size="small"
                    icon={<EditOutlined />}
                    onClick={() => handleEditSnippet(snippet)}
                  />
                </Tooltip>,
                <Popconfirm
                  title="确定删除这个代码片段吗？"
                  onConfirm={() => handleDeleteSnippet(snippet.id)}
                  okText="删除"
                  cancelText="取消"
                >
                  <Button
                    type="text"
                    size="small"
                    icon={<DeleteOutlined />}
                    danger
                  />
                </Popconfirm>,
              ]}
            >
              <List.Item.Meta
                avatar={<CodeOutlined style={{ fontSize: 20, color: '#1890ff' }} />}
                title={
                  <Space>
                    <Button
                      type="link"
                      style={{ padding: 0, height: 'auto' }}
                      onClick={() => handleInsertSnippet(snippet)}
                    >
                      {snippet.name}
                    </Button>
                    <Tag color="blue">{snippet.category}</Tag>
                    {snippet.usageCount > 0 && (
                      <Text type="secondary" style={{ fontSize: 12 }}>
                        使用 {snippet.usageCount} 次
                      </Text>
                    )}
                  </Space>
                }
                description={
                  <div>
                    <Paragraph
                      style={{ margin: '4px 0', color: '#666' }}
                      ellipsis={{ rows: 2 }}
                    >
                      {snippet.description}
                    </Paragraph>
                    <Space wrap>
                      {snippet.tags.map(tag => (
                        <Tag key={tag} size="small">{tag}</Tag>
                      ))}
                    </Space>
                    <div style={{ marginTop: 8 }}>
                      <Text
                        code
                        style={{
                          fontSize: 12,
                          background: '#f5f5f5',
                          padding: '2px 4px',
                          borderRadius: 2,
                          display: 'block',
                          whiteSpace: 'pre-wrap',
                          maxHeight: 60,
                          overflow: 'hidden',
                        }}
                      >
                        {snippet.sql.length > 100 
                          ? snippet.sql.substring(0, 100) + '...'
                          : snippet.sql
                        }
                      </Text>
                    </div>
                  </div>
                }
              />
            </List.Item>
          )}
          locale={{ emptyText: '没有找到匹配的代码片段' }}
        />
      </Drawer>

      {/* 编辑/新建模态框 */}
      <Modal
        title={editingSnippet ? '编辑代码片段' : '新建代码片段'}
        open={editModalVisible}
        onCancel={() => {
          setEditModalVisible(false)
          setEditingSnippet(null)
          form.resetFields()
        }}
        onOk={handleSaveSnippet}
        width={800}
        okText="保存"
        cancelText="取消"
      >
        <Form
          form={form}
          layout="vertical"
          requiredMark={false}
        >
          <Form.Item
            name="name"
            label="片段名称"
            rules={[{ required: true, message: '请输入片段名称' }]}
          >
            <Input placeholder="输入代码片段名称" />
          </Form.Item>

          <Form.Item
            name="description"
            label="描述"
            rules={[{ required: true, message: '请输入描述' }]}
          >
            <Input placeholder="输入代码片段描述" />
          </Form.Item>

          <Form.Item
            name="category"
            label="分类"
            rules={[{ required: true, message: '请输入分类' }]}
          >
            <Input placeholder="输入分类名称" />
          </Form.Item>

          <Form.Item
            name="tags"
            label="标签"
          >
            <Input placeholder="输入标签，用逗号分隔" />
          </Form.Item>

          <Form.Item
            name="sql"
            label="SQL代码"
            rules={[{ required: true, message: '请输入SQL代码' }]}
          >
            <TextArea
              rows={10}
              placeholder="输入SQL代码，可以使用 ${n:placeholder} 格式定义模板变量"
              style={{ fontFamily: 'Monaco, Consolas, monospace' }}
            />
          </Form.Item>

          <div style={{ fontSize: 12, color: '#666', marginTop: -16 }}>
            <Text type="secondary">
              提示：使用 $&#123;1:column_name&#125; 格式定义模板变量，数字表示Tab顺序
            </Text>
          </div>
        </Form>
      </Modal>
    </>
  )
}

export default SQLSnippets